package com.ftg.learn.chapter02.java.myframework.util;

import com.ftg.learn.chapter02.java.pool.Animals;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 动物工厂  -
 *
 * @author kangjx
 * @version 1.0
 * @date 2023/12/25 下午3:32
 */
@SuppressWarnings("all")
public class AnimalsFactory {

    /**
     * 容器
     */
    private Map<String,Animals> containers = new HashMap<>();

    /**
     * 获取动物
     * @param name
     * @return
     */
    public Animals getAnimals(String name) {
        return this.containers.get(name);
    }

    /**
     * 构造函数
     * @param path
     */
    public AnimalsFactory(String path){
       this.open(path);
    }

    /**
     * 第一种
     * @param clazz
     * @param name
     * @param type
     * @param color
     * @return
     * @param <T>
     */
    public <T extends Animals> T animalsFactory(Class<T> clazz, String name, String type, String color) {
        T animals =  createInstance3(clazz);
        animals.setName(name);
        animals.setType(type);
        animals.setColor(color);
        return animals;
    }

    public <T> T createInstance3(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 打开货源 进货.xml
     */
    public void open(String path){
        //货源 进货 .xml dom4j
        SAXReader saxReader = new SAXReader();
        try {
            Document read = saxReader.read(path);
            Element dayi = read.getRootElement();

            List<Element> animals = dayi.elements();

            for (Element animal : animals) {
                Attribute key = animal.attribute("key");
                Attribute value = animal.attribute("value");

                Element name = animal.element("name");
                String nameVal = name.getText();

                Element type = animal.element("type");
                String typeVal = type.getText();

                Element color = animal.element("color");
                String colorVal = color.getText();
                try {
                    Class clazz = Class.forName(value.getValue());
                    Animals obj = this.animalsFactory(clazz,nameVal,typeVal,colorVal);
                    containers.put(key.getValue(),obj);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }

        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }

    }


}
